#include "e2d/core/physics/RigidbodyDynamic.h"
#include "e2d/core/physics/PhysicsSystem.h"
#include "e2d/core/trans/TransformNode.h"

#include "e2d/core/Entity.h"

void e2d::RigidbodyDynamic::Delete()
{
	auto& scene = e2d::PxUtils::gScene;
	auto& physics = e2d::PxUtils::gPhysics;
	
	if (m_PxRgDynamic)
	{
		scene->removeActor(*m_PxRgDynamic);
		m_PxRgDynamic->release();
		m_PxRgDynamic = 0;
	}
	
	m_PxShapeMaps.Delete();


}

void e2d::RigidbodyDynamic::Create()
{
	Delete();

	auto scene = e2d::PxUtils::gScene;
	auto physics = e2d::PxUtils::gPhysics;

	const auto& transformNode = m_Entity->GetConst<e2d::TransformNode>();

	auto world = transformNode.m_World;
	m_PxRgDynamic = physics->createRigidDynamic(e2d::PxUtils::toPxTransform(world));
	//m_PxRgDynamic->setActorFlag(physx::PxActorFlag::eDISABLE_SIMULATION, true);

	scene->addActor(*m_PxRgDynamic);

	m_PxShapeMaps.Create();
	m_PxShapeMaps.AttachedToRigidBody(m_PxRgDynamic);



}
void e2d::RigidbodyDynamic::PushTransform()
{
	//if (m_PxRgDynamic)
	//{
	//	const auto& transformNode = m_Entity->GetConst<e2d::TransformNode>();
	//	m_PxRgDynamic->setGlobalPose(e2d::PxUtils::toPxTransform(transformNode.m_World));
	//}
}

void e2d::RigidbodyDynamic::OnLoad()
{
	Delete();
	Create();


}

void e2d::RigidbodyDynamic::OnStart()
{
}

void e2d::RigidbodyDynamic::OnUpdate()
{
}

void e2d::RigidbodyDynamic::OnUpdateRuntime()
{
	if (!m_Entity->m_Exist)
	{
		return;
	}
	if (!m_PxRgDynamic)
	{
		return;
	}
	auto& transformNode = m_Entity->Get<e2d::TransformNode>();

	const auto pxTransform = m_PxRgDynamic->getGlobalPose();

	auto pullTransform = e2d::PxUtils::toGlmTransform(pxTransform);
	auto originScale = transformNode.m_World.m_Scale;
	pullTransform.m_Scale = originScale;

	transformNode.SetWorldTransform(pullTransform);
	transformNode.m_Local.Fixed();

}

void e2d::RigidbodyDynamic::OnDestroy()
{
}
